import React, { useState, useEffect } from "react";
import * as pdfjsLib from "pdfjs-dist";
import { diffWords } from "diff";
import { PDFDocument, StandardFonts, rgb } from "pdf-lib";
import { create } from "fontkit"; // 导入 fontkit
import fontBytes from "./NotoSansSC-VariableFont_wght.ttf"; // 引入字体文件
pdfjsLib.GlobalWorkerOptions.workerSrc = "/pdf.worker.mjs";
console.log(fontBytes);
const PdfCompare = ({ pdf1, pdf2 }) => {
  const [diffText, setDiffText] = useState(null);
  const [diffPdfUrl, setDiffPdfUrl] = useState(null);

  // 提取 PDF 中的文本
  const extractTextFromPdf = async (pdfUrl) => {
    const pdf = await pdfjsLib.getDocument(pdfUrl).promise;
    let textContent = "";
    const numPages = pdf.numPages;

    for (let pageNum = 1; pageNum <= numPages; pageNum++) {
      const page = await pdf.getPage(pageNum);
      const content = await page.getTextContent();
      content.items.forEach((item) => {
        textContent += item.str + " ";
      });
    }

    return textContent;
  };

  // 比较文本差异，返回纯文本差异
  const compareTextDiff = (text1, text2) => {
    const diffs = diffWords(text1, text2);
    // 返回一个包含文本差异的数组
    return diffs
      .map((part) => {
        if (part.added) {
          return `<span style="background-color: lightgreen">${part.value}</span>`;
        } else if (part.removed) {
          return `<span style="background-color: lightcoral">${part.value}</span>`;
        } else {
          return part.value;
        }
      })
      .join(""); // 连接为单一字符串
  };

  // 生成包含差异的 PDF
  const createPdfWithTextDiff = async (diffText) => {
    console.log(diffText);
    
    const pdfDoc = await PDFDocument.create();
    // 注册 fontkit 实例
    // const fontkitInstance = await create();
    // pdfDoc.registerFontkit(fontkitInstance);
    const page = pdfDoc.addPage([600, 800]);
    const { width, height } = page.getSize();

    // 将差异文本拆分为行
    const font = await pdfDoc.embedFont(StandardFonts.TimesRoman);
    const fontSize = 12;
    const lines = diffText.split("\n");
    let yOffset = height - fontSize * 2;

    // 为每行添加文本到 PDF 中
    lines.forEach((line) => {
      page.drawText(line, {
        x: 50,
        y: yOffset,
        font,
        size: fontSize,
        color: rgb(0, 0, 0),
      });
      yOffset -= fontSize * 1.5;
    });

    const pdfBytes = await pdfDoc.save();
    const diffBlob = new Blob([pdfBytes], { type: "application/pdf" });
    return URL.createObjectURL(diffBlob);
  };

  // 获取文本差异并生成 PDF
  const comparePdfs = async () => {

    const text1 = await extractTextFromPdf(pdf1);
    const text2 = await extractTextFromPdf(pdf2);

    // 比较文本差异并生成 HTML 格式的差异文本
    const diffResult = compareTextDiff(text1, text2);
    setDiffText(diffResult);

    // 生成包含差异的 PDF
    const diffPdfUrl = await createPdfWithTextDiff(diffResult);
    setDiffPdfUrl(diffPdfUrl);
  };

  useEffect(() => {
    comparePdfs();
  }, [pdf1, pdf2]);

  return (
    <div>
      <h1>PDF 文本对比结果</h1>
      <div dangerouslySetInnerHTML={{ __html: diffText }} />
      {diffPdfUrl && (
        <div>
          <h2>预览包含差异的 PDF：</h2>
          <iframe
            src={diffPdfUrl}
            width="100%"
            height="600px"
            title="Diff PDF Preview"
          />
        </div>
      )}
    </div>
  );
};

export default PdfCompare;
